from sqlalchemy import or_
from app import db
from app.models.department import Department


class DepartmentService:
    """部门服务层"""
    
    @staticmethod
    def get_list(page=1, per_page=10, keyword=None, status=None):
        """获取部门列表"""
        query = Department.query
        
        # 关键词搜索
        if keyword:
            query = query.filter(or_(
                Department.name.like(f'%{keyword}%'),
                Department.manager.like(f'%{keyword}%')
            ))
        
        # 状态筛选
        if status is not None:
            query = query.filter(Department.status == status)
        
        # 按排序字段和创建时间排列
        query = query.order_by(Department.order_num, Department.create_time.desc())
        
        return query, page, per_page
    
    @staticmethod
    def get_tree():
        """获取部门树形结构"""
        departments = Department.query.filter_by(status=True, parent_id=None)\
                                    .order_by(Department.order_num).all()
        return [dept.to_tree_dict() for dept in departments]
    
    @staticmethod
    def get_by_id(dept_id):
        """根据ID获取部门"""
        return Department.query.get(dept_id)
    
    @staticmethod
    def create(data):
        """创建部门"""
        department = Department()
        department.parent_id = data.get('parent_id')
        department.name = data.get('name')
        department.manager = data.get('manager')
        department.phone = data.get('phone')
        department.email = data.get('email')
        department.status = data.get('status', True)
        department.order_num = data.get('order_num', 0)
        
        db.session.add(department)
        db.session.commit()
        return department
    
    @staticmethod
    def update(dept_id, data):
        """更新部门"""
        department = Department.query.get(dept_id)
        if not department:
            return None
        
        department.parent_id = data.get('parent_id', department.parent_id)
        department.name = data.get('name', department.name)
        department.manager = data.get('manager', department.manager)
        department.phone = data.get('phone', department.phone)
        department.email = data.get('email', department.email)
        department.status = data.get('status', department.status)
        department.order_num = data.get('order_num', department.order_num)
        
        db.session.commit()
        return department
    
    @staticmethod
    def delete(dept_id):
        """删除部门"""
        department = Department.query.get(dept_id)
        if not department:
            return False
        
        # 检查是否有子部门
        if department.children:
            return False, "该部门存在子部门，无法删除"
        
        # 检查是否有关联的管理员
        if department.admins:
            return False, "该部门下存在管理员，无法删除"
        
        db.session.delete(department)
        db.session.commit()
        return True, "删除成功"
    
    @staticmethod
    def get_parent_options():
        """获取父部门选项"""
        departments = Department.query.filter_by(status=True).all()
        return [{'id': dept.id, 'name': dept.name} for dept in departments] 